<template>
  <!-- 订单列表 -->
  <div>
    <!-- 模糊搜索 -->
    <el-card  style="height: 70px; margin-bottom: 20px;" :body-style="{ padding: '10px', height: '50px', width: '100%'}">
      <div class="box-card-div">
        <el-form :inline="true" :model="AttendanceRecordsDTO" ref="AttendanceRecordsDTOForm" class="demo-form-inline">
          <!-- 展示打卡开始时间 -->
          <el-form-item label="开始日期" prop="AttendanceDate">
            <el-date-picker
              size="small"
              v-model="AttendanceRecordsDTO.AttendanceDate"
              type="datetime"
              placeholder="打卡开始日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <!-- 展示打卡结束时间 -->
          <el-form-item label="结束日期" prop="AttendanceDate2">
            <el-date-picker
              size="small"
              v-model="AttendanceRecordsDTO.AttendanceDate2"
              type="datetime"
              placeholder="打卡结束日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="success" round size="middle" @click="findAll" icon="el-icon-search" style="width: 100px;">搜索</el-button>
            <el-button type="warning" round size="middle" @click="resetOrderForm('AttendanceRecordsDTOForm')"
                       icon="el-icon-refresh-left" style="width: 100px;">重置</el-button>
            <el-button type="primary" round size="middle"
                       @click="handleCheckIn" icon="el-icon-time" style="width: 120px;">上班打卡</el-button>
            <el-button type="info" round size="middle"
                       @click="handleCheckOut" icon="el-icon-time" style="width: 120px;">下班打卡</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 共用打卡确认弹窗 -->
    <el-dialog
      :title="currentCheckType === 'checkIn' ? '上班打卡确认' : '下班打卡确认'"
      :visible.sync="checkDialogVisible"
      width="30%">

      <div>
        <p>是否确认{{ currentCheckType === 'checkIn' ? '上班打卡' : '下班打卡' }}？</p>
        <p><strong>当前时间：</strong>{{ checkTime }}</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="checkDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCheck">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 添加和批量删除按钮 -->
    <!--<div class="button-container">-->
    <!--  <el-button class="btn_add" type="primary" @click="handleAddOrder" size="middle" icon="el-icon-plus">新增</el-button>-->
    <!--  <el-button class="btb_del" type="danger" @click="deleteOrderBatch" size="middle" icon="el-icon-delete">批量删除</el-button>-->
    <!--  <el-button class="btb_del" type="primary" @click="uploadExcelDialog = true" size="middle" icon="el-icon-delete">导入</el-button>-->
    <!--  <el-button class="btb_del" type="warning" @click="deleteOrderBatch" size="middle" icon="el-icon-delete">导出</el-button>-->
    <!--</div>-->
    <!--<el-dialog-->
    <!--  :title="title"-->
    <!--  :visible.sync="editDialogVisible"-->
    <!--  width="40%"-->
    <!--  :close-on-click-modal="false"-->
    <!--&gt;-->
    <!--  <el-form ref="orderForm" :model="AttendanceRecordsList" :rules="rules" label-width="100px">-->
    <!--    <el-form-item label="订单号" prop="orderNo">-->
    <!--      <el-input v-model="AttendanceRecordsList.orderNo"></el-input>-->
    <!--    </el-form-item>-->
    <!--    <el-form-item label="用户名" prop="username">-->
    <!--      <el-input v-model="orderList.username"></el-input>-->
    <!--    </el-form-item>-->
    <!--    <el-form-item label="订单总金额" prop="totalAmount">-->
    <!--      <el-input v-model.number="orderList.totalAmount"></el-input>-->
    <!--    </el-form-item>-->
    <!--    <el-form-item label="订单状态" prop="orderStatus">-->
    <!--      <el-select v-model="orderList.orderStatus">-->
    <!--        <el-option label="待发货" value="0"></el-option>-->
    <!--        <el-option label="已发货" value="1"></el-option>-->
    <!--        <el-option label="已完成" value="2"></el-option>-->
    <!--        <el-option label="退款中" value="3"></el-option>-->
    <!--        <el-option label="已关闭" value="4"></el-option>-->
    <!--      </el-select>-->
    <!--    </el-form-item>-->
    <!--    <el-form-item label="支付时间" prop="payTime">-->
    <!--      <el-date-picker-->
    <!--        v-model="orderList.payTime"-->
    <!--        type="datetime"-->
    <!--        placeholder="选择支付时间"-->
    <!--        style="width: 100%"-->
    <!--      ></el-date-picker>-->
    <!--    </el-form-item>-->
    <!--    <el-form-item label="发货时间" prop="deliveryTime">-->
    <!--      <el-date-picker-->
    <!--        v-model="orderList.deliveryTime"-->
    <!--        type="datetime"-->
    <!--        placeholder="选择发货时间"-->
    <!--        style="width: 100%"-->
    <!--      ></el-date-picker>-->
    <!--    </el-form-item>-->
    <!--    <el-form-item label="收货时间" prop="receiveTime">-->
    <!--      <el-date-picker-->
    <!--        v-model="orderList.receiveTime"-->
    <!--        type="datetime"-->
    <!--        placeholder="选择收货时间"-->
    <!--        style="width: 100%"-->
    <!--      ></el-date-picker>-->
    <!--    </el-form-item>-->
    <!--  </el-form>-->
    <!--  <div slot="footer" class="dialog-footer">-->
    <!--    <el-button @click="resetOrderForm('orderForm')">取 消</el-button>-->
    <!--    <el-button type="primary" @click="saveOrder('orderForm')">确 定</el-button>-->
    <!--  </div>-->
    <!--</el-dialog>-->

    <!-- 上传文件对话框 -->
    <!--<el-dialog-->
    <!--  title="上传订单数据"-->
    <!--  width="26%"-->
    <!--  :visible.sync="uploadExcelDialog"-->
    <!--  :close-on-click-modal="false"-->
    <!--&gt;-->
    <!--  &lt;!&ndash;上传组件&ndash;&gt;-->
    <!--  <el-upload-->
    <!--    class="upload-demo"-->
    <!--    drag-->
    <!--    action=""-->
    <!--    :before-upload="beforeUpload"-->
    <!--    :file-list="fileList"-->
    <!--    :http-request="uploadExcelFun"-->
    <!--    :on-change="handleChange"-->
    <!--  >-->
    <!--    <i class="el-icon-upload"></i>-->
    <!--    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
    <!--  </el-upload>-->
    <!--  <div slot="footer" class="dialog-footer">-->
    <!--    <el-button @click="uploadExcelDialog = false">取 消</el-button>-->
    <!--    <el-button type="primary" @click="">确 定</el-button>-->
    <!--  </div>-->
    <!--</el-dialog>-->

    <!-- 统计本月正常出勤、迟到、早退和旷工次数（不考虑节假日） -->
    <div class="attendance-statistics" style="display: flex; align-items: center; font-size: 23px; font-weight: bold; margin-bottom: 20px; margin-top: 20px; gap: 20px; margin-left: 20px;  width: 100%;height: auto;">
      <div class="attendance-statistics-item">
        <span class="attendance-statistics-item-title">本月正常出勤:{{this.attendanceStats.normal + "次"}}</span>
      </div>
      <div class="attendance-statistics-item">
        <span class="attendance-statistics-item-value">迟到:{{this.attendanceStats.late + "次"}}</span>
      </div>
      <div class="attendance-statistics-item">
        <span class="attendance-statistics-item-value">早退:{{this.attendanceStats.early + "次"}}</span>
      </div>
      <div class="attendance-statistics-item">
        <span class="attendance-statistics-item-value">旷工:{{this.attendanceStats.absent + "次"}}</span>
      </div>
    </div>


    <!-- 打卡记录列表 -->
    <el-card class="order-list">
      <el-table
        :data="tableData"
        border
        class="order-table"
        style="width: 100%"
        height="500"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 展示复选框 -->
        <el-table-column type="selection" width="30px"></el-table-column>
        <!-- 展示编号 -->
        <el-table-column prop="id" label="编号" width="50px"></el-table-column>
        <!-- 展示用户名 -->
        <el-table-column prop="username" label="用户名"></el-table-column>
        <!-- 展示上午打卡时间 -->
        <el-table-column prop="morningCheckInTime" label="上午">
          <template slot-scope="scope">
              <span v-if="scope.row.morningCheckInTime">{{ scope.row.morningCheckTime}}</span>
            <span v-else>暂无记录</span>
          </template>
        </el-table-column>
        <!-- 展示下午打卡时间 -->
        <el-table-column prop="AfternoonCheckOutTime" label="下午">
          <template slot-scope="scope">
            <span v-if="scope.row.AfternoonCheckOutTime">{{ scope.row.AfternoonCheckOutTime}}</span>
            <span v-else>暂无记录</span>
          </template>
        </el-table-column>
        <!--展示打开状态  打卡状态，方便统计:1正常、2:迟到、3:早退、4:旷工-->
        <el-table-column prop="status" label="打卡状态">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'primary' : scope.row.status === 3 ? 'warning' :  'danger' "
            >
              {{ scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '迟到' : scope.row.status === 3 ? '早退' : '旷工'}}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 展示操作按钮 -->
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="handleOrderEdit(scope.$index, scope.row)"
              style="margin-right: 5px; margin-bottom: 2px"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleOrderDelete(scope.$index, scope.row)"
              style="margin-bottom: 2px"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 分页导航 -->
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="pageSizes"
            :page-size="AttendanceRecordsDTO.pageSize"
            :current-page="AttendanceRecordsDTO.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
          <!-- 添加一个跳转按钮 -->
          <el-button style="margin-right: 10px" size="small" type="primary" @click="toPage">跳转</el-button>
        </div>
      </div>
    </el-card>
  </div>

</template>

<script>

import { checkIn, checkOut, findAll, getAttendanceStats } from '@/api/attendanceRecords'
import moment from 'moment'
import { formatDate } from 'element-ui/src/utils/date-util'

export default {
  name: 'AttendanceRecords',
  data() {
    return {
      // 获取登录用户的userId
      userId: this.$store.state.user.userId,
      checkDialogVisible: false, // 控制打卡弹窗显示
      currentCheckType: '',      // 当前打卡类型：'checkIn' / 'checkOut'
      checkTime:null,
      title:"添加打卡记录",  // 用于添加、修改订单的对话框的标题
      tableData: [],   // 表格数据
      // 统计本月正常出勤、迟到、早退和旷工次数（不考虑节假日）
      attendanceStats: {
        normal: 0,     // 正常出勤（status === 0）
        late: 0,       // 迟到（status === 2）
        early: 0,      // 早退（status === 3）
        absent: 0      // 旷工（status === 4）
      },
      AttendanceRecordsDTO:{
        pageNum: 1,
        pageSize: 3,
        AttendanceDate: null,
        AttendanceDate2: null,
        morningCheckInTime: null,
        AfternoonCheckOutTime: null,
      },
      total: 0, // 总条数
      AttendanceRecordsList: {},  // 用于添加、修改的对话框
      pageSizes: [3, 5, 10, 20], // 分页尺寸
      editDialogVisible: false, // 编辑对话框是否显示也用于添加对话框
      multipleSelection:[], // 用于批量删除的复选框

    }
  },
  methods: {
    formatDate,
    // 模糊查询+分页处理
    findAll() {
      // 先对日期进行格式化处理
      const params = { ...this.AttendanceRecordsDTO };

      if (params.AttendanceDate) {
        params.AttendanceDate = moment(params.AttendanceDate).format('YYYY-MM-DD HH:mm:ss');
      }
      if (params.AttendanceDate2) {
        params.AttendanceDate2 = moment(params.AttendanceDate2).format('YYYY-MM-DD HH:mm:ss');
      }
      findAll(params).then(res => {
        // 返回成功
        this.tableData = res.data.list
        // 处理一下日期格式
        res.data.list.forEach(item => {
          item.morningCheckTime = item.morningCheckInTime ? this.$moment(item.morningCheckInTime).format('YYYY-MM-DD HH:mm:ss') : '';
          item.afternoonCheckTime = item.AfternoonCheckOutTime ? this.$moment(item.AfternoonCheckOutTime).format('YYYY-MM-DD HH:mm:ss') : '';
        })
        this.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    // 分页的两个绑定事件
    handleSizeChange(size) {
      this.AttendanceRecordsDTO.pageSize = size;
      this.findAll();
    },
    handleCurrentChange(currentPage) {
      this.AttendanceRecordsDTO.pageNum = currentPage;
      this.findAll();
    },
    // 跳转到指定页
    toPage() {
      this.findAll();
    },

    // 统计考勤状态
    fetchAttendanceStats() {
      // 假设你有一个新的 API 方法
      getAttendanceStats().then(res => {
        if (res.code === 20000) {
          this.attendanceStats = res.data;
        }
      }).catch(err => {
        console.error('获取考勤统计失败', err);
      });
    },
    // 复选框点击事件
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    },

    // 上班打卡
    handleCheckIn() {
      this.currentCheckType = 'checkIn';
      // 给出当前时间
      const now = new Date();
      const nowStr = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
      this.checkTime = nowStr;
      this.checkDialogVisible = true;
    },

    // 下班打卡
    handleCheckOut() {
      this.currentCheckType = 'checkOut';
      const now = new Date();
      const nowStr = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
      this.checkTime = nowStr;
      this.checkDialogVisible = true;
    },

    // 提交打卡
    submitCheck() {
      // 判断当前的打卡类型
      const isCheckIn = this.currentCheckType === 'checkIn';
      const now = new Date();
      const nowStr = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

      // 调用接口
      if (isCheckIn) {
        // 调用上班打卡接口
        this.AttendanceRecordsDTO.AttendanceDate = nowStr;
        this.AttendanceRecordsDTO.userId = this.userId;
        checkIn(this.AttendanceRecordsDTO).then(res => {
          if (res.code === 20000) {
            this.$message.success('上班打卡成功');
            this.findAll(); // 刷新数据
          } else if (res.code === 400){
            this.$message.error('您已经上班打卡，无法重复打卡');
          } else {
            this.$message.error('上班打卡失败');
          }
        });
      } else {
        // 调用下班打卡接口
        this.AttendanceRecordsDTO.AttendanceDate = nowStr;
        this.AttendanceRecordsDTO.userId = this.userId;
        checkOut(this.AttendanceRecordsDTO).then(res => {
          if (res.code === 20000) {
            this.$message.success('下班打卡成功');
            this.findAll(); // 刷新数据
          } else if (res.code === 400){
            this.$message.error('您还未上班打卡，无法下班打卡');
          } else {
            this.$message.error('下班打卡失败');
          }
        });
      }

      // 关闭弹窗
      this.checkDialogVisible = false;
    },



    // 通过订单id删除订单
    handleOrderDelete(index, row) {
      // 首先要进行弹框提示
      this.$confirm("是否确认删除订单编号为" + '"' + row.id + '"' + "的数据项？", '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const orderId = row.id;
        deleteOrder(orderId).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderDTO.pageNum = 1;
            this.findAll()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 批量删除订单
    deleteOrderBatch(){
      this.$confirm("是否确认删除选中的" + this.multipleSelection.length + "条数据项？", '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrderBatch(this.multipleSelection).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderDTO.pageNum = 1;
            this.findAll()
            // 批量删除成功后，需要清空已选择的行
            this.multipleSelection = [];
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 点击修改按钮，触发修改对话框
    async handleOrderEdit(index, row) {
      this.title = "修改订单";
      this.editDialogVisible = true;
      // 等待对话框完全打开
      this.$nextTick(() => {
        // 先重置表单（这会清除所有校验状态）
        this.$refs.orderForm.resetFields();
        // 清除校验状态
        this.$refs.orderForm.clearValidate();
        // 深拷贝数据
        this.orderList = JSON.parse(JSON.stringify(row));
        this.orderList.username = row.user.username;
        // 转换日期格式为 Date 对象
        this.convertToDatePickerFormat(this.orderList);
      });
    },
    resetFields() {
      this.$refs.orderForm.resetFields();
    },
    // 添加一个专门处理日期字段的方法
    convertDateFields() {
      const dateFields = ['AttendanceRecordsDTO.AttendanceDate', 'deliveryTime', 'receiveTime'];
      dateFields.forEach(field => {
        if (this.orderList[field]) {
          this.orderList[field] = new Date(this.orderList[field]);
        }
      });
    },
    // 点击新增按钮，触发新增对话框
    handleAddOrder() {
      this.title = "添加订单";
      this.orderList = {
        payTime: '',
        deliveryTime: '',
        receiveTime: ''
      };
      this.editDialogVisible = true;
      this.$refs.orderForm.resetFields(); // 重置表单校验状态
    },

    formatDateFields() {
      const dateFields = ['attendanceDate', 'attendanceDate2'];
      dateFields.forEach(field => {
        if (this.AttendanceRecordsDTO[field] instanceof Date) {
          this.AttendanceRecordsDTO[field] = this.$moment(this.AttendanceRecordsDTO[field]).format('YYYY-MM-DD HH:mm:ss');
        }
      });
    },

    // 点击保存按钮，触发保存事件
    saveOrder(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 格式化日期字段
          this.formatDateFields();

          if (this.title === "添加订单") {
            addOrder(this.orderList).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '新增成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderDTO.pageNum = 1;
                this.findAll()
                this.resetOrderForm('orderForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '新增失败!',
                  duration: 1000
                })
              }
            })
          } else {
            updateOrder(this.orderList).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderDTO.pageNum = 1;
                this.findAll()
                this.resetOrderForm('orderForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败!',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false;
        }
      })
    },
    // 重置表单
    resetOrderForm(formName) {
      // 关闭对话框
      this.editDialogVisible = false;
      // 延迟一下，确保表单控件都渲染完毕
      this.$nextTick(() => {
        this.$refs[formName].resetFields(); // 重置表单校验状态
      });
    },
  },
  created() {
    this.findAll();
    this.fetchAttendanceStats();
    // 打印出userId
    console.log("userId--------------" + this.userId)
  },
}
</script>

<style scoped>
/* 表格整体样式 */
.el-table {
  margin-bottom: 20px;
  font-size: 13px;
  border: 1px solid #ebeef5;
}

/* 表头样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
  text-align: center;
  white-space: nowrap;
}

/* 单元格样式 */
.el-table td {
  text-align: center;
  padding: 10px 0;
  border-color: #ebeef5;
}

/* 操作按钮的间距调整 */
button.el-button {
  margin: 2px;
  width: 80px; /* 固定按钮宽度 */
}
.pagination-container{
  align-items: center;
  justify-content: center;  /* 居中 */
  display: flex;   /* 使其成为一个flex容器 */
  margin-top: 10px;
}
.button-container {
  display: flex;
  margin-left: 30px;
  width: 100px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  margin-top: 20px;
}

.button-container .btn_add{
  margin-right: 10px;
  text-align: center;
  font-size: 16px;
  width: 100px;
  border-top-left-radius: 5px;
}

.button-container .btb_del{
  margin-right: 10px;
  text-align: center;
  font-size: 14px;
  width: 150px;
  border-top-left-radius: 5px;
}
.order-list{
  padding: 0;
}
.order-table{
  margin-top: 20px;
}
</style>

